<?php

namespace App\Http\Controllers\Admin\OrderManager;

use App\Enums\ExportEnum;
use App\Enums\RedisKeyEnum;
use App\Jobs\QiPao\ExcelJob;
use App\Services\Tools\Export;
use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Services\Tools\ExportService;
use Illuminate\Http\Request;

//引用http请求类
use App\Response\Response;

class AlipayDrawController extends BaseController
{

    /**
     * @api {post} /order/alipay-draw/check 支付宝提现-批量审核
     * @apiVersion 0.1.0
     * @apiName 订单管理-支付宝提现-批量审核
     * @apiGroup 订单管理
     * @apiParam {number} ids                         记录id，逗号分隔  必传
     * @apiParam {number} type                        1 通过 2 拒绝  必传
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function check(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'ids'       => 'required|string',
                'type'      => 'required|numeric|integer|in:1,2',
                'remark'    => 'string',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $params = $request->input();

        $res = app('repo_user_withdraw');

        $idArr = explode(",", $params['ids']);
        $type = $params['type'];
        $remark = $params['remark'] ?? '';

        $rows = $res->batchCheck($idArr, $type, $remark);
        if (!$rows) {
            throw new BasicException(10001, "审核失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {post} /order/alipay-draw/remark 支付宝提现-备注
     * @apiVersion 0.1.0
     * @apiName 订单管理-支付宝提现-备注
     * @apiGroup 订单管理
     * @apiParam {int} id
     * @apiParam {string} remark                       备注 必传
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function remark(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'id' => 'required|integer',
                'remark' => 'required|string',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }
        $id = $request->input('id');

        $rows = app('repo_user_withdraw')->setRemark($id, $request->input());
        if (!$rows) {
            throw new BasicException(10001, "备注失败！");
        }

        return Response::sendData(true);
    }


    /**
     * @api {get} /order/alipay-draw 支付宝提现-列表
     * @apiVersion 0.1.0
     * @apiName 订单管理-支付宝提现-列表
     * @apiGroup 订单管理
     * @apiParam {number} type 来源  1从app提现2从h5提现 可选
     * @apiParam {string} remark 备注 可选
     * @apiParam {string} bank_num 账号 可选
     * @apiParam {number} bank_type 账号 1.支付宝  2.微信 3.银行卡 可选
     * @apiParam {string} real_name 姓名 可选
     * @apiParam {number} user_code 用户编号 可选
     * @apiParam {number} status 状态 1.待审核 2.通过 3.拒绝 可选
     * @apiParam {string} start_time 开始时间 可选
     * @apiParam {string} end_time  结束时间 可选
     * @apiParam {string} mobile  手机号 可选
     * @apiParam {number} page  页码 可选
     * @apiParam {number} perPage  分页容量 可选
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "list": [
     * {
     * "id(序号)": 31398,
     * "user_code(用户编号)": 617040,
     * "money(提现金额)": "89900.00",
     * "cardholder(姓名)": "周亮",
     * "bank_num(支付宝账号)": "zl880915zl@163.com",
     * "add_time(申请时间)": "2020-11-02 22:26:20",
     * "audit_time(审批时间)": "2020-11-12 16:09:16",
     * "type(来源)": 2,
     * "status(状态)": 3,
     * "remark(备注)": "123",
     * "mobile(手机号)": "18658172093",
     * "origin_mobile(预留手机号)": "18658172093",
     * "bank_name(开户行)": "支付宝",
     * "bank_zhi(支行)": "",
     * "card_number(身份证)": "",
     * "bank_type(类别 1.支付宝  2.微信 3.银行卡)": 1,
     * "gold(提现金币)": 8990000
     * }
     * ],
     * "meta": {
     * "page": 1,
     * "limit": 10,
     * "next": null,
     * "total": 1
     * }
     * }
     * }
     */
    public function list(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'remark'              => 'filled|string',
                'bank_num'            => 'filled|string',
                'real_name'           => 'filled|string',
                'mobile'              => 'filled|string',
                'user_code'           => 'filled|numeric|integer',
                'status'              => 'filled|numeric|integer|in:1,2,3',
                'platform_status'     => 'filled|numeric|integer|in:1,2,3',
                'bank_type'           => 'filled|numeric|integer|in:1,2,3',
                'start_time'          => 'filled|string|date_format:Y-m-d',
                'end_time'            => 'filled|string|date_format:Y-m-d',
                'audit_start_time'    => 'filled|string|date_format:Y-m-d',
                'audit_end_time'      => 'filled|string|date_format:Y-m-d',
                'operate_start_time'  => 'filled|string|date_format:Y-m-d',
                'operate_end_time'    => 'filled|string|date_format:Y-m-d',
                'page'                => 'filled|numeric',
                'perPage'             => 'filled|numeric',
                'card_number'         => 'filled|string',               //身份证号
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, $v->errors()->first());
        }

        $params = $request->input();

        $list = app('repo_user_withdraw')->getAliWithDrawQueryList($params);
        return Response::sendStatList($list);
    }

    /**
     * @api {get} /order/alipay-draw/export/excel 支付宝提现-导出数据
     * @apiVersion 0.1.0
     * @apiName 支付宝提现-导出数据
     * @apiGroup 订单管理
     * @apiParam {number} type 来源  1从app提现2从h5提现 可选
     * @apiParam {string} remark 备注 可选
     * @apiParam {string} bank_num 账号 可选
     * @apiParam {string} real_name 姓名 可选
     * @apiParam {number} user_code 用户编号 可选
     * @apiParam {number} status 状态 1.待审核 2.通过 3.拒绝 可选
     * @apiParam {string} start_time 开始时间 可选
     * @apiParam {string} end_time  结束时间 可选
     * @apiParam {string} mobile  手机号 可选
     * @apiParam {number} bank_type 账号 1.支付宝  2.微信 3.银行卡 可选
     * @apiParam {number} page  页码 可选
     * @apiParam {number} perPage  分页容量 可选
     * @apiSuccessExample 成功响应
     *  {
     *   "code": 200,
     *   "data": {
     *       "download_url": "asdasdasd.com"
     *       }
     *  }
     */
    public function export(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'remark'     => 'filled|string',
                'bank_num'   => 'filled|string',
                'real_name'  => 'filled|string',
                'user_code'  => 'filled|numeric|integer',
                'status'     => 'filled|numeric|integer|in:1,2,3',
                'start_time' => 'filled|string|date_format:Y-m-d',
                'end_time'   => 'filled|string|date_format:Y-m-d',
                'page'       => 'filled|numeric',
                'perPage'    => 'filled|numeric',
                'mobile'     => 'filled|string',
                'bank_type'  => 'filled|numeric|integer|in:1,2,3',
                'type'       => 'filled|numeric|integer|in:1,2',
                'card_number'             => 'filled|string',               //身份证号
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }
        $params = $request->input();
        $params['perPage'] = 10000;
        $params['page'] = 1;
        $listData = app('repo_user_withdraw')->getAliWithDrawQueryList($params);
        $list = $listData['lists'];

        //        "id(序号)": 31398,
        //        "user_code(用户编号)": 617040,
        //        "money(提现金额)": "89900.00",
        //        "cardholder(姓名)": "周亮",
        //        "bank_num(支付宝账号)": "zl880915zl@163.com",
        //        "add_time(申请时间)": "2020-11-02 22:26:20",
        //        "audit_time(审批时间)": "2020-11-12 16:09:16",
        //        "type(来源)": 2,
        //        "status(状态)": 3,
        //        "remark(备注)": "123",
        //        "mobile(手机号)": "18658172093",
        //        "origin_mobile(预留手机号)": "18658172093",
        //        "bank_name(开户行)": "支付宝",
        //        "bank_zhi(支行)": "",
        //        "card_number(身份证)": "",
        //        "bank_type(类别 1.支付宝  2.微信 3.银行卡)": 1,
        //        "gold(提现金币)": 8990000
        $bank_type_arr = [1 => "支付宝", 2 => "微信", 3 => "银行卡"];
        $status_arr = [1 => "待审核", 2 => "通过", 3 => "拒绝"];
        $type_arr = [1 => "app", 2 => "h5"];

        if ($list) {
            if ($params['bank_type'] == 1) {
                $fields = [
                    ['field' => 'id', 'header' => '序号（必填）', 'width' => '15'],
                    ['field' => 'bank_num', 'header' => '收款方支付宝账号（必填）', 'width' => '26'],
                    ['field' => 'cardholder', 'header' => '收款方姓名（必填）', 'width' => '20'],
                    ['field' => 'money', 'header' => '金额（必填，单位：元）', 'width' => '24'],
                    ['field' => 'remark', 'header' => '备注（选填）', 'width' => '24'],
                    ['field' => 'add_time', 'header' => '申请时间', 'width' => '20'],
                    ['field' => 'audit_time', 'header' => '审批时间', 'width' => '20'],
                    ['field' => 'user_code', 'header' => '用户编号', 'width' => '15'],
                    ['field' => 'tmobile', 'header' => '手机号', 'width' => '20'],
                    ['field' => 'id_number', 'header' => '身份证号', 'width' => '20'],
                ];

                $downloadUrl = Export::exportUsePhpOffice('alipay-withdraw', $fields, $list->toArray()['data'], 'A1:E1');

                //记录日志
                app('model_admin_export_log')->add(8, $params, $downloadUrl);

                return Response::sendData([
                    'download_url' => $downloadUrl,
                ]);
            } else {
                $result = [];
                foreach ($list as $item) {
                    $temp = [
                        $item->id,
                        $item->user_code,
                        $item->money,
                        $item->cardholder,
                        $item->bank_num,
                        $item->add_time,
                        $item->audit_time,
                        $type_arr[$item->type],
                        $status_arr[$item->status],
                        $item->remark,
                        $item->mobile,
                        $item->origin_mobile,
                        $item->bank_name,
                        $item->bank_zhi,
                        $item->card_number,
                        $bank_type_arr[$item->bank_type],
                        $item->gold,
                    ];
                    $result[] = $temp;
                }

                $headings = [
                    "序号",
                    "用户编号",
                    "提现金额",
                    "姓名",
                    "支付宝账号",
                    "申请时间",
                    "审批时间",
                    "来源",
                    "状态",
                    "备注",
                    "手机号",
                    "预留手机号",
                    "开户行",
                    "支行",
                    "身份证",
                    "类别",
                    "提现金币",
                ];

                return app('repo_export')->export(8, $params, $headings, $result);
            }
        }
    }

    /**
     * @api {get} /order/alipay-draw/export/excel/async 支付宝提现-导出数据
     * @apiVersion 0.1.0
     * @apiName 支付宝提现-导出数据
     * @apiGroup 订单管理
     * @apiParam {number} type 来源  1从app提现2从h5提现 可选
     * @apiParam {string} remark 备注 可选
     * @apiParam {string} bank_num 账号 可选
     * @apiParam {string} real_name 姓名 可选
     * @apiParam {number} user_code 用户编号 可选
     * @apiParam {number} status 状态 1.待审核 2.通过 3.拒绝 可选
     * @apiParam {string} start_time 开始时间 可选
     * @apiParam {string} end_time  结束时间 可选
     * @apiParam {string} mobile  手机号 可选
     * @apiParam {number} bank_type 账号 1.支付宝  2.微信 3.银行卡 可选
     * @apiSuccessExample 成功响应
     *  {
     *   "code": 200,
     *   "data": {
     *       "download_url": "asdasdasd.com"
     *       }
     *  }
     */
    public function exportAsync(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'remark'     => 'filled|string',
                'bank_num'   => 'filled|string',
                'real_name'  => 'filled|string',
                'user_code'  => 'filled|numeric|integer',
                'status'     => 'filled|numeric|integer|in:1,2,3',
                'start_time' => 'filled|string|date_format:Y-m-d',
                'end_time'   => 'filled|string|date_format:Y-m-d',
                'mobile'     => 'filled|string',
                'bank_type'  => 'filled|numeric|integer|in:1,2,3',
                'type'       => 'filled|numeric|integer|in:1,2',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }
        $params = $request->only(['remark', 'bank_num', 'real_name', 'user_code', 'status', 'start_time', 'end_time', 'mobile', 'bank_type', 'type']);
        $data = [
            'admin_id'     => $request->admin_id ?? '',
            'data_no'      => 8,//ExportEnum::NO
            'condition'    => json_encode($params) ?? '',
            'status'       => 0,//正在导出
            'title'        => '支付宝提现日志 异步导出',//正在导出
            'download_url' => '',
        ];
        $exportLogId = app('model_admin_export_log')->insertGetId($data);
        $excel = new ExcelJob($exportLogId, $request->admin_id, 8, $params);
        // 标记导出程序开始运行
        dispatch($excel)->onQueue(env('RABBITMQ_QUEUE_EXCEL'));                    //推送到指定队列

        return Response::sendData('');
    }

    /**
     * 设置自动通过审核
     * @param Request $request
     * @return string
     * @throws BasicException
     */
    public function setAutoCheck(Request $request)
    {
        $params = $request->only('switch_status');
        $v = app('validator')->make($params, [

        ]);
        if ($v->fails()) {
            throw new BasicException(10001, $v->errors()->first());
        }
        $switchValue = $params['switch_status'] ?? 0;
        $key = sprintf(RedisKeyEnum::AUTO_ZFB_RECHARGE_ORDER, 1);
        $redis = app('redis');
        $result = $redis->set($key,$switchValue);
        return Response::sendData($result);
    }

    /**
     * 获取自动审核状态
     * @return string
     */
    public function getAutoCheck()
    {
        $key = sprintf(RedisKeyEnum::AUTO_ZFB_RECHARGE_ORDER, 1);
        $redis = app('redis');
        $result['switch_status'] = $redis->get($key);
        return Response::sendData($result);
    }

}
